package test;

//岛屿的最大面积：https://leetcode.cn/problems/max-area-of-island/description/
public class MaxAreaOfIsland {
    int m,n,sum;
    int[] dx={0,0,1,-1};
    int[] dy={1,-1,0,0};
    boolean[][] visit;
    public void dfs(int[][] grid,int i,int j){
        sum+=grid[i][j]; 
        for(int k=0;k<4;k++){
            int x=i+dx[k],y=j+dy[k];
            if(x>=0&&y>=0&&x<m&&y<n&&visit[x][y]==false&&grid[x][y]==1){
                visit[x][y]=true;
                dfs(grid,x,y,sum);
            }
        } 
        area=Math.max(area,sum);        
    }
    public int maxAreaOfIsland(int[][] grid) {
        int area=0;
        m=grid.length;
        n=grid[0].length;
        visit=new boolean[m][n];
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                if(visit[i][j]==false&&grid[i][j]==1){
                	sum=0;
                    visit[i][j]=true;
                    dfs(grid,i,j);
                    area=Math.max(area, sum);
                }
            }
        }
        return area;
    }
}
